package com.wlcb.jpower.chat.reply.handler.chain;

import com.alibaba.fastjson.JSONObject;
import com.wlcb.jpower.chat.reply.ReplyEntity;
import com.wlcb.jpower.chat.reply.ReplyHandler;
import com.wlcb.jpower.chat.service.OtherService;
import com.wlcb.jpower.chat.service.impl.OtherServiceImpl;
import com.wlcb.jpower.im.cache.ImChatRecordCache;
import com.wlcb.jpower.im.model.DataPacket;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.utils.CollectionUtil;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.module.common.utils.SpringUtil;
import com.wlcb.jpower.properties.JpowerChatProperties;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;

import java.util.Comparator;
import java.util.List;

/**
 * @author: liwenfei
 * @desc:
 */
@Slf4j
public class OtherReplyHandler extends ReplyHandler {
    private static OtherService otherService;
    private static JpowerChatProperties properties;

    static {
        properties = SpringUtil.getBean(JpowerChatProperties.class);
        otherService = SpringUtil.getBean(OtherServiceImpl.class);
    }


    @Override
    public ReplyEntity handler(DataPacket dataPacket, WxMpXmlMessage wxMessage) {
        if (CollectionUtil.isEmpty(properties.getOthers())) {
            return this.getNextHandler().handler(dataPacket, wxMessage);
        }

        try {
            log.debug("进入第三方回复");
            List<JpowerChatProperties.Other> others = properties.getOthers();
            others.sort(Comparator.comparing(JpowerChatProperties.Other::getSort));

            for (JpowerChatProperties.Other other : others) {
                if (Fc.isNoneBlank(other.getUrl()) && CollectionUtil.isNotEmpty(other.getAppIds()) && Fc.contains(other.getAppIds(), dataPacket.getAppId())) {
                    log.debug("开始请求:{},APPID={}", other.getUrl(), dataPacket.getAppId());
                    String res = otherService.request(other.getUrl(), dataPacket.getAppId(), wxMessage);
                    ResponseData<String> responseData = JSONObject.parseObject(res, ResponseData.class);
                    if (responseData.isStatus() && Fc.isNotBlank(responseData.getData())) {
                        ReplyEntity kefu = ReplyEntity.singleTextMessage(responseData.getData(), true).kefu();
                        kefu.setAppId(dataPacket.getAppId());
                        kefu.setToUser(wxMessage.getFromUser());
                        return kefu;
                    }
                }
            }
            return this.getNextHandler().handler(dataPacket, wxMessage);
        } catch (Exception e) {
            return new ExceptionHandler(dataPacket.getAppId(), "第三方回复", e).handler(dataPacket, wxMessage);
        }
    }

    @Override
    public ReplyEntity handler(DataPacket dataPacket, WxMpXmlMessage wxMessage, ImChatRecordCache cache) {
        return null;
    }
}
